//
//  FDHomeController.m
//  FamousDoctorOnline
//
//  Created by wszyxc on 16/7/5.
//  Copyright © 2016年 wszyxc. All rights reserved.
//

#import <CoreLocation/CoreLocation.h>

#import "FDHomeController.h"
#import "FDDiseaseSubdivideViewController.h"
#import "FDBaseViewVC.h"
#import "FDProvinceViewController.h"
#import "FDPublicServiceVC.h"

#import "WZHCycleView.h"
#import "FDContentView.h"
#import "FDWeatherView.h"
#import "FDTitleView.h"
#import "FDDocterInfoController.h"

#import "FDButton.h"
#import "FDWeatherModel.h"
#import "WZHUserDefaults.h"
#import "FDBarcodeController.h"
#import "SVProgressHUD.h"

@interface FDHomeController ()<wzhCycleViewDelegate,CLLocationManagerDelegate>

//weatherView
@property (weak,nonatomic) FDWeatherView * weatherView;

//cycleView
@property (weak,nonatomic) WZHCycleView * cycleView;

//titleView:名医通标题视图
@property (weak,nonatomic) UIView * titleView;

//名医通内容视图
@property (weak,nonatomic) FDContentView * contentView;

//内容视图的图片数组

@property (strong,nonatomic) NSArray * imgArray;

//内容视图的标签文字数组
@property (strong,nonatomic) NSArray * wordArray;

//获取天气数组
@property (nonatomic, strong) NSArray<FDWeatherModel *> *weathers;

@property (nonatomic, strong) CLLocationManager* locationManager;

//城市
@property (nonatomic, copy) NSString *city;
@property (nonatomic, copy) NSString *GPSCity;
@end


#define  kNavMaxY  64
#define  kWeatherH 70
#define kCity @"City"

@implementation FDHomeController

- (void)viewDidLoad {
    

    [self dismissViewControllerAnimated:YES completion:nil];

    
        [self GPSLoad];
        
        [super viewDidLoad];
        
        [self setupUI];
        
        [self setSubViewBlock];
    

    
}

- (void)GPSLoad{

    //检测定位功能是否开启
    if([CLLocationManager locationServicesEnabled]){
        if(!_locationManager){
            self.locationManager = [[CLLocationManager alloc] init];
            if([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
                
                [self.locationManager requestWhenInUseAuthorization];
                [self.locationManager requestAlwaysAuthorization];
            }
            //设置代理
            [self.locationManager setDelegate:self];
            //设置定位精度
            [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
            //设置距离筛选
            [self.locationManager setDistanceFilter:100];
            //开始定位
            [self.locationManager startUpdatingLocation];
            //设置开始识别方向
            [self.locationManager startUpdatingHeading];
        }
    }else{
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil
                                                             message:@"您没有开启定位功能"
                                                            delegate:nil
                                                   cancelButtonTitle:@"确定"
                                                   otherButtonTitles:nil, nil];
        [alertView show];
    }

}

#pragma mark - CLLocationManangerDelegate
//定位成功以后调用
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

    [self.locationManager stopUpdatingLocation];
    CLLocation* location = locations.lastObject;
    [self reverseGeocoder:location];
}

#pragma mark Geocoder
//反地理编码
- (void)reverseGeocoder:(CLLocation *)currentLocation {

    CLGeocoder* geocoder = [[CLGeocoder alloc] init];
    
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        
        if(error || placemarks.count == 0){
            NSLog(@"error = %@",error);
        }else if(error != nil){
            NSLog(@"An error occurred = %@", error);
        }else{
            
            CLPlacemark* placemark = placemarks.firstObject;

            NSString *string = [[placemark addressDictionary] objectForKey:@"City"];
            self.GPSCity = [[string componentsSeparatedByString:@"市"]firstObject];
            NSLog(@"%@",_GPSCity);
                    [self loadWeather:YES];
//            [WZHUserDefaults WZHSaveObject:GPSCity forKey:kOtherCity];
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"你的位置" message:[[placemark addressDictionary] objectForKey:@"City"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
        }
        
    }];

}

- (void)setupUI{
    
    self.title = @"名医在线";
    
    self.view.backgroundColor = [UIColor grayColor];
    
    [self.navigationController.navigationBar setBarTintColor:kThemeColor];
    
    //添加扫一扫
    UIBarButtonItem *scan = [[UIBarButtonItem alloc]initWithTitle:@"二维码" style:UITableViewRowActionStyleDefault target:self action:@selector(clickScanButton)];
    
    scan.tintColor = WHITE_COLOR;
    
    self.navigationItem.rightBarButtonItem = scan;
    
    //添加天气预报的视图
    [self setupWeatherView];
    
    //添加图片轮播器视图
    [self setupCycleView];
    
    //添加名医通标题视图
    [self setupFamousDoctorTongTitleView];
    
    //添加名医通的内容视图
    [self setupFamousDoctorContentView];
    
}

/**
 *  设置天气的view
 */
- (void)setupWeatherView{
    
    FDWeatherView *weatherView = [[FDWeatherView alloc]init];
    
    weatherView.owner = self;
    
    self.weatherView = weatherView;
    
    [self.view addSubview:weatherView];
    
    [weatherView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.leading.trailing.offset(0);
        make.top.offset(kNavMaxY);
        make.height.offset(kWeatherH);
        
    }];
    
}

/**
 *  添加一个label的快捷方法
 */
- (UILabel *)setupOneLabelWithTitle:(NSString *)title testColor:(UIColor *)color fontSize:(CGFloat)fontSize{
    
    UILabel *label = [[UILabel alloc]init];
    
    label.textColor = color;
    
    label.font = [UIFont systemFontOfSize:fontSize];
    
    label.text = title;
    
    return label;
    
}

/**
 *  设置图片轮播器
 */

- (void)setupCycleView{
    
    WZHCycleView *cycleView = [WZHCycleView wzhCycleViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 140)];
    
    self.cycleView = cycleView;
    
    cycleView.timeDelay = 2;
    cycleView.autoCycle = YES;
    
    cycleView.netImage = YES;
    
    cycleView.delegate = self;
    
    [self.view addSubview:cycleView];
    
    [cycleView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.leading.trailing.offset(0);
        make.top.equalTo(self.weatherView.mas_bottom).offset(0);
        make.height.offset(140);
        
    }];
    
}

#pragma mark - 图片轮播器的代理方法

- (NSArray<NSString *> *)imageArrayForWZHCycleView{
    
    NSArray *imageArray = @[
                            @"http://img.guahao.com/portal_upload/rollingnews/1453447883150.jpg",
                            @"http://img.guahao.com/portal_upload/mediafocus/1461826474435.jpg",
                            @"http://img.guahao.com/portal_upload/rollingnews/1461574027543.jpg"
                            ];
    //这里提供图片名数组即可,没有就会使用默认的假数据
    
    return imageArray;
}

/**
 *  设置名医通标题视图
 */

- (void)setupFamousDoctorTongTitleView{
    
    //实例化titleView
    FDTitleView *titleView = [[FDTitleView alloc]init];
    
    self.titleView = titleView;
    
    [self.view addSubview:titleView];
    
    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.leading.trailing.offset(0);
        make.top.equalTo(self.cycleView.mas_bottom).offset(0);
        make.height.offset(60);
    }];
    
}

/**
 *  设置名医通内容视图
 */

- (void)setupFamousDoctorContentView{
    
    FDContentView *contentView = [[FDContentView alloc]init];
    
    self.contentView = contentView;
    
    contentView.backgroundColor = [UIColor grayColor];
    
    [self.view addSubview:contentView];
    
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.titleView.mas_bottom).offset(0);
        make.leading.trailing.bottom.offset(0);
        
    }];
    
    //添加6个小视图,小视图上面有一个button和一个label
    
    NSInteger count = 6;
    
    for (int i =0; i<count; i++) {
        
        UIView *smallView = [[UIView alloc]init];
        
        [self.contentView addSubview:smallView];
        
        smallView.backgroundColor = WHITE_COLOR;
        
        //添加button
        FDButton *btn = [FDButton buttonWithType:UIButtonTypeCustom];
        
        btn.tag=i;
        
        UIImage *origImage = [[UIImage imageNamed:self.imgArray[i]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        
        [btn setImage: origImage forState:UIControlStateNormal];
        
        [btn setTitle:self.wordArray[i] forState:UIControlStateNormal];
        
        btn.titleLabel.font = kFDFont;
        
        
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [smallView addSubview:btn];
        
      
        
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.leading.trailing.top.bottom.offset(0);
            
        }];
        
        
    }
    
}


/**
 *  按钮点击方法
 */

- (void)btnClick:(UIButton *)btn{
    

    //获取登陆状态,未登录就提示且不予进入子功能
    
    BOOL logState = [WZHUserDefaults WZHBoolForKey:@"isLogin"];
    
    if (!logState) {
        
        [SVProgressHUD showErrorWithStatus:@"您当前未登录,不能使用该功能!"];
        
        [self performSelector:@selector(dismissSV) withObject:nil afterDelay:2];
        
        return;
        
    }
    

    if (btn.tag==5) {
        
        FDPublicServiceVC *pubVC=[[FDPublicServiceVC alloc]init];
        pubVC.title=self.wordArray[btn.tag];
        
        [self.navigationController pushViewController:pubVC animated:YES];
        
    }else{
        
        FDBaseViewVC *baseVC=[[FDBaseViewVC alloc]init];
        
        baseVC.title=self.wordArray[btn.tag];
        baseVC.titleText=self.wordArray[btn.tag];
        
        [self.navigationController pushViewController:baseVC animated:YES];
    }

}

/**
 *  SV消失
 */
- (void)dismissSV{
    
    [SVProgressHUD dismiss];
    
}



#pragma mark  - 懒加载

- (NSArray *)imgArray{
    if (!_imgArray) {
        _imgArray = @[@"zl",@"xyg",@"sj",@"xy",@"gt",@"gy"];
    }
    return _imgArray;
}

- (NSArray *)wordArray{
    if (!_wordArray) {
        _wordArray = @[@"肿瘤",@"心血管",@"神经",@"血液科",@"骨科",@"公益"];
    }
    return _wordArray;
}

//取出偏好设置中存储的数据
- (void)loadWeather:(BOOL)isCompare{

    if (YES) {
    //当系统启动时加载网络的key值
        _city = _GPSCity;

    }else{
    //启动之后获取plist的值
        _city = [WZHUserDefaults WZHObjectForKey:kCity];
    }
    
    
    if (!_city) {
        _city = @"温岭";
    }
    [self loadCurDayWeather:_city];
}

//加载json数据
- (void)loadCurDayWeather:(NSString *)city{

    __weak typeof(self) weakSelf = self;
    [[FDWeatherModel shareManager]loadWeatherWithCity:city success:^(NSArray<FDWeatherModel *> *headlineList) {
        weakSelf.weathers = headlineList;
    } error:^{
        NSLog(@"error");
    }];
}

//选择城市
- (void)setSubViewBlock{
    
    __weak typeof(self) weakSelf = self;
    self.weatherView.selectCityBlock = ^{
        
        FDProvinceViewController *vc = [[FDProvinceViewController alloc] init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
        
        
    };
}

- (void)setWeathers:(NSArray<FDWeatherModel *> *)weathers{
    _weathers = weathers;
    self.weatherView.dataList = weathers;
    
}

-(void)clickScanButton
{
    FDBarcodeController *barcode = [[FDBarcodeController alloc]init];
    [self.navigationController pushViewController:barcode animated:YES];
}

@end
